package com.hushan.thread;

/**
 * Created by hushan on 2017/8/3.
 */
public class Counter implements Runnable {
    private int count;

    public Counter() {
        count = 0;
    }

    public int getCount() {
        return count;
    }

    // 加上同步锁
    public void syncCount() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + ":" + (count++));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //非synchronized代码块，未对count进行读写操作，所以可以不用synchronized
    public void printCount() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + " count:" + count);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void run() {
        String threadName = Thread.currentThread().getName();
        if (threadName.equals("printCount")) {
            printCount();
        }else if (threadName.equals("syncCount")) {
            syncCount();
        }
    }
}
